/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cs575.coresystem;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.Timestamp;
/**
 *
 * @author bms
 */
public class Utils {
    
    private static final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
    public static Timestamp dateFormat(Date rawData) throws DateConversionException
    {
        Timestamp time = null;
        try{          
            time = Timestamp.valueOf(format.format(rawData)); 
        }
        catch(Exception e){
            throw new DateConversionException();
        }
        return time;
    }
    
    public static Timestamp dateFormat(String strData) throws DateConversionException
    {
        Timestamp time = null;
        try{
            time = new Timestamp(format.parse(strData).getTime()); 
        }
        catch(Exception e){
            throw new DateConversionException();
        }
        return time;
    }
    
    
    public static Timestamp dateFormat(Timestamp strData) throws DateConversionException
    {
        Timestamp time = null;
        try{
            time = new Timestamp(format.parse(strData.toString()).getTime()); 
        }
        catch(Exception e){
            throw new DateConversionException();
        }
        return time;
    }
    
    
    /**
     * Serialize any objects before passing them to the web service
     * 
     * @param o - any custom data object
     * @return 
     */
    public static String serialize(Object o) {
        String s;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        XMLEncoder encoder = new XMLEncoder( new BufferedOutputStream( stream ) );

        encoder.writeObject(o);
        encoder.close();
        s = stream.toString();
        return s;
    }

    
    /**
     * De-serialize any objects received from the web service
     * 
     * @param s
     * @return 
     */
    public static Object deserialize(String s) {
        XMLDecoder decoder = new XMLDecoder( new ByteArrayInputStream( s.getBytes() ) );
        return decoder.readObject();
    }    
    
    
}
